package core;

/**
 * Time-of-day server listening to port 6013.
 *
 * Figure 3.26
 *
 * @author Gagne, Galvin, Silberschatz Operating System Concepts with Java -
 * Eighth Edition Copyright John Wiley & Sons - 2010.
 */
import java.net.*;
import java.io.*;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Server {
    private ServerSocket sock = null;
    private int port = 6000;

    public int getPort() {
        return port;
    }
    
    public Server() {
        this(new Random().nextInt(65535)+1);
    }
    
    public Server(int _port) {
        try {
            port = _port;
            sock = new ServerSocket(port);
            System.out.println("Server created on port " + port);
            // now listen for connections
            while (true) {
                Socket client = sock.accept();
                if(client.isConnected()) {
                    System.out.println("Client " + client.toString() + " connected to server!");
                }
                // we have a connection
                PrintWriter pout = new PrintWriter(client.getOutputStream(), true);
                // write the Date to the socket
                pout.println(new java.util.Date().toString());
                client.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
